package com.hxzy.shop.utils;

import cn.hutool.core.util.ObjectUtil;
import com.hxzy.shop.vo.ApiException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @Description：图片<-->base
 * @Author tu-jia-hao
 * @Data 2022/6/22 17:14
 */

public class ImgTransfersBetweenBase64Util {


    /*
    * 图片转base64
    * */
    public static String imgToBase64(String path){
        if(ObjectUtil.isEmpty(path)||"".equals(path)){
            return null;
        }
        byte[] data = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try{
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            in = connection.getInputStream();
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len =in.read(b)) != -1){
                out.write(b,0,len);
            }
        }catch (Exception e){
            throw new ApiException(500,"图片转化Base64异常");
        }finally {
            try{
                if(in != null ){
                    in.close();
                }
            }catch (IOException e){
                e.getStackTrace();
            }
        }
        BASE64Encoder base = new BASE64Encoder();
        return "data:image/png;base64,"+base.encode(out.toByteArray());
    }

    /**
     * URL图片转BASE64
     */
    public static String urlToBase64(String path){
        HttpGet httpGet = new HttpGet(path);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            String s = Base64.getEncoder().encodeToString(bytes);
            return "data:image/png;base64,"+s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
